//Accepted
#include <cstdio>
#include <map>
#include <iostream>
using namespace std;

map<int, int> mm;


int  z, i, m, l, t=1, x, a;

int main(){
	//freopen("in.txt","r",stdin);

	scanf("%d%d%d%d", &z, &i, &m, &l);
	while(z&&i&&m&&l){
		mm.clear();
		x=1;
		a=l;
		
		while(1)
			if(mm[a]){//colisao
				break;
			}
			else {
				mm[a]=x++;
				a=(z*a+i)%m;
			}
		printf("Case %d: %d\n", t++, x-mm[a]);
		scanf("%d%d%d%d", &z, &i, &m, &l);
	}
	return 0;
}
